package com.kfm.spring.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.sql.DataSource;


@Configuration
@ComponentScan({"com.kfm.spring.service", "com.kfm.spring.log", "com.kfm.spring.controller"})
@EnableAspectJAutoProxy
@EnableTransactionManagement
@Import({DBConfig.class})
@EnableWebMvc
public class SpringConfig implements WebMvcConfigurer {

    /**
     * 配置SqlSessionFactoryBean
     * @return
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 设置别名包
        sqlSessionFactoryBean.setTypeAliasesPackage("com.kfm.spring.domain");
        return sqlSessionFactoryBean;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        // 设置mapper接口所在的包
        mapperScannerConfigurer.setBasePackage("com.kfm.spring.mapper");
        return mapperScannerConfigurer;
    }


    /**
     * 配置事务管理器
     * @param dataSource
     * @return
     */
    @Bean
    public TransactionManager transactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
}
